'use strict';

let gulp = require("gulp")
let sourcemaps = require("gulp-sourcemaps")
let babel = require("gulp-babel")
let concat = require("gulp-concat")
let rename = require("gulp-rename")
let uglify = require('gulp-uglify')
let cleanCSS = require('gulp-clean-css')
let notify = require('gulp-notify')
let imageMin = require('gulp-imagemin')
let htmlmin = require('gulp-htmlmin') //压缩html

gulp.task("to-es5", function () {
    return gulp.src("js/*.js")
        .pipe(sourcemaps.init())
        .pipe(babel())
        .pipe(sourcemaps.write("."))
        .pipe(gulp.dest("dist/main"))
})

gulp.task('min-js', ["to-es5"], function () {
    // 1. 找到文件
    return gulp.src('dist/main/*.js')
    // 2. 压缩文件
        .pipe(uglify())
        .pipe(rename({suffix: '.min'}))
        // 3. 另存压缩后的文件
        .pipe(gulp.dest("dist/js"))
        .pipe(notify({message: 'js task success'}))
})

// 压缩 css 文件
gulp.task('min-css', function () {
    // 1. 找到文件
    return gulp.src('css/*.css')
    // 2. 压缩文件
        .pipe(cleanCSS())
        .pipe(rename({suffix: '.min'}))
        // 3. 另存压缩后的文件
        .pipe(gulp.dest('dist/css'))
        .pipe(notify({message: 'css task success'}))
})

gulp.task('min-html', function () {
    let options = {
        removeComments: true, //清除HTML注释
        collapseWhitespace: true, //压缩HTML
        minfyJS: true,//压缩JS
        minfyCss: true,//压缩CSS
    }
    gulp.src('html/*.html')
    //压缩html
        .pipe(htmlmin(options))
        //压缩后的名字44
        .pipe(gulp.dest('dist/html'))
})

gulp.task('min-image',function(){
    gulp.src('images/*.{png,jpg,gif,ico}')
        // .pipe(imageMin({progressive: true}))
        .pipe(gulp.dest('dist/images'))
})

gulp.task('auto', function () {
    // 监听文件修改，当文件被修改则执行 script 任务
    gulp.watch('js/*.js', ['min-js'])
    gulp.watch('css/*.css', ['min-css'])
})

gulp.task('build', ['min-css', 'min-js', 'min-html'])